package com.itheima.appserver.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.itheima.appserver.config.MyCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;

/**
 * 响应体通知增强
 *
 * @Author: lqTao
 * @Date: 2021/12/9 16:20
 */
@ControllerAdvice
public class CacheResponseBody implements ResponseBodyAdvice {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    //如果返回值为true则进入到下一个方法
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.hasMethodAnnotation(MyCache.class) && returnType.hasMethodAnnotation(GetMapping.class);

    }

    //增强响应体
    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        //判断响应体是否为空
        if (ObjectUtil.isNull(body)) {
            return null;
        }

       /* String redisValue = null;
        if (body instanceof String) {
            redisValue = (String) body;
        } else {
            redisValue = JSONUtil.toJsonStr(body);
        }*/

        //把响应体转换为json数据
        String jsonStr = JSONUtil.toJsonStr(body);
        //获取redis的key
        String key = CacheInterceptor.cacheKey(((ServletServerHttpRequest) request).getServletRequest());
        //获取缓存时间
        MyCache time = returnType.getMethodAnnotation(MyCache.class);
        //把数据存入redis
        redisTemplate.opsForValue().set(key,jsonStr,time.cacheTime(), TimeUnit.SECONDS);
        System.out.println("把数据存入redis");

        return body;
    }
}
